<template>
  <div class="api-test-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span style="font-size: 18px; font-weight: bold">接口测试报告</span>
          <div>
            <el-button type="primary" @click="loadData" :loading="loading">
              {{ loading ? '加载中...' : '刷新数据' }}
            </el-button>
            <el-tag type="success" style="margin-left: 8px">
              总计: {{ data.length }} 个接口
            </el-tag>
            <el-tag type="danger" style="margin-left: 8px">
              失败: {{ failedCount }} 个
            </el-tag>
            <el-tag type="primary" style="margin-left: 8px">
              成功率: {{ successRate }}%
            </el-tag>
          </div>
        </div>
      </template>

      <el-table
        :data="data"
        style="width: 100%"
        :row-class-name="getRowClassName"
        stripe
        border
        v-loading="loading"
        @row-click="handleRowClick"
        empty-text="暂无数据"
      >
        <!-- 接口名称 -->
        <el-table-column
          prop="接口名称"
          label="接口名称"
          width="150"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <span :class="{ 'highlight-text': hasAssertionDetail(row) }">
              {{ row.接口名称 }}
            </span>
          </template>
        </el-table-column>

        <!-- 基础URL -->
        <el-table-column
          prop="基础URL"
          label="基础URL"
          min-width="200"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <span :class="{ 'highlight-text': hasAssertionDetail(row) }">
              {{ formatUrl(row.基础URL) }}
            </span>
          </template>
        </el-table-column>

        <!-- 请求方法 -->
        <el-table-column prop="请求方法" label="方法" width="80" align="center">
          <template #default="{ row }">
            <el-tag
              :type="getMethodType(row.请求方法)"
              :class="{ 'highlight-tag': hasAssertionDetail(row) }"
            >
              {{ row.请求方法 }}
            </el-tag>
          </template>
        </el-table-column>

        <!-- HTTP状态码 -->
        <el-table-column
          prop="HTTP状态码"
          label="状态码"
          width="100"
          align="center"
        >
          <template #default="{ row }">
            <el-tag
              :type="getStatusType(row.HTTP状态码)"
              :class="{ 'highlight-tag': row.HTTP状态码 != '200' }"
            >
              {{ row.HTTP状态码 }}
            </el-tag>
          </template>
        </el-table-column>

        <!-- 断言详情结果 -->
        <el-table-column
          prop="断言详情结果"
          label="断言结果"
          width="100"
          align="center"
        >
          <template #default="{ row }">
            <el-tag
              v-if="row.断言详情结果"
              :type="hasAsserDetail(row) ? 'danger' : 'success'"
              :class="{ 'highlight-tag': hasAsserDetail(row) }"
            >
              {{ hasAsserDetail(row) ? '失败' : '通过' }}
            </el-tag>
            <el-tag v-else :type="row.断言失败数 !== '0' ? 'warning' : 'info'">
              {{ hasAsserDetail(row) ? '失败' : '通过' }}
            </el-tag>
          </template>
        </el-table-column>

        <!-- 断言失败数 -->
        <el-table-column
          prop="断言失败数"
          label="失败数"
          width="80"
          align="center"
        >
          <template #default="{ row }">
            <span
              :class="{
                'highlight-text': hasAssertionDetail(row),
                'error-count': row.断言失败数 !== '0',
              }"
            >
              {{ row.断言失败数 }}
            </span>
          </template>
        </el-table-column>

        <!-- 响应耗时 -->
        <el-table-column
          prop="响应耗时"
          label="耗时"
          width="100"
          align="center"
        >
          <template #default="{ row }">
            <span :class="{ 'highlight-text': hasAssertionDetail(row) }">
              {{ row.响应耗时 }}
            </span>
          </template>
        </el-table-column>

        <!-- 操作 -->
        <el-table-column label="操作" width="120" align="center" fixed="right">
          <template #default="{ row }">
            <el-button
              size="small"
              @click.stop="showDetail(row)"
              :type="hasAssertionDetail(row) ? 'warning' : 'primary'"
            >
              {{ hasAssertionDetail(row) ? '详情' : '查看' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      :title="currentRow ? `接口详情 - ${currentRow['接口名称']}` : '接口详情'"
      width="70%"
    >
      <div v-if="currentRow" class="detail-content">
        <!-- 基本信息 -->
        <el-descriptions title="基本信息" :column="2" border>
          <el-descriptions-item label="接口名称">
            {{ currentRow.接口名称 }}
          </el-descriptions-item>
          <el-descriptions-item label="基础URL">
            {{ currentRow.基础URL }}
          </el-descriptions-item>
          <el-descriptions-item label="请求方法">
            <el-tag :type="getMethodType(currentRow.请求方法)">
              {{ currentRow.请求方法 }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="HTTP状态码">
            <el-tag :type="getStatusType(currentRow.HTTP状态码)">
              {{ currentRow.HTTP状态码 }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="响应耗时">
            {{ currentRow.响应耗时 }}
          </el-descriptions-item>
          <el-descriptions-item label="返回数据大小">
            {{ currentRow.返回数据大小 }}
          </el-descriptions-item>
          <el-descriptions-item label="请求ID" :span="2">
            <el-text type="info" style="font-size: 12px">
              {{ currentRow.请求ID }}
            </el-text>
          </el-descriptions-item>
        </el-descriptions>

        <!-- 断言信息 -->
        <el-descriptions
          v-if="currentRow.断言通过数"
          title="断言信息"
          :column="1"
          border
          style="margin-top: 20px"
        >
          <el-descriptions-item label="断言通过数" label-width="100">
            <el-tag type="success">{{ currentRow.断言通过数 }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="断言失败数" label-width="100">
            <el-tag type="danger">{{ currentRow.断言失败数 }}</el-tag>
          </el-descriptions-item>
        </el-descriptions>

        <!-- 断言详情 -->
        <!-- <div v-if="hasAssertionDetail(currentRow)" class="assertion-detail"> -->
        <div v-if="currentRow.断言详情名称" class="assertion-detail">
          <el-divider />
          <div
            v-for="(item, index) in currentRow.断言详情名称"
            :key="index"
            style="margin-bottom: 20px"
          >
            <el-descriptions title="断言详情" :column="1" border for>
              <el-descriptions-item label="断言名称" label-width="100">
                <el-tag type="warning">
                  {{ currentRow.断言详情名称[index] }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="断言结果" label-width="100">
                <el-tag
                  :type="
                    currentRow.断言详情结果[index] === '失败'
                      ? 'danger'
                      : 'success'
                  "
                >
                  {{ currentRow.断言详情结果[index] }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="断言内容" label-width="100">
                <pre class="assertion-content">{{
                  currentRow.断言详情内容[index]
                }}</pre>
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </div>

        <!-- URL参数 -->
        <el-descriptions
          title="URL参数"
          :column="1"
          border
          style="margin-top: 10px"
        >
          <el-descriptions-item label="参数详情">
            <pre class="url-params">{{
              JSON.stringify(currentRow.URL参数, null, 2)
            }}</pre>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>
  
  <script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import {
  reqGetApiReportInfo,
  reqGetOneApiReportInfo,
} from '@/api/api_auto/report'
import { da } from 'element-plus/es/locale'
// defineOptions({
//   name: 'ReportError',
// })
// 定义数据类型
interface URLParams {
  [key: string]: string | string[]
}

interface ApiTestData {
  HTTP状态码: string
  URL参数: URLParams
  响应耗时: string
  基础URL: string
  接口名称: string
  断言失败数: string
  断言通过数: string
  请求ID: string
  请求URL: string
  请求方法: string
  返回数据大小: string
  断言详情内容: [string]
  断言详情名称: [string]
  断言详情结果: [string]
}

// 响应式数据
const data = ref<ApiTestData[]>([])
const loading = ref(false)
const detailVisible = ref(false)
const currentRow = ref<ApiTestData | null>(null)

// 模拟接口数据
// const mockApiTestData: ApiTestData[] = [
//   {
//     HTTP状态码: '200',
//     URL参数: {
//       loc: 'CN',
//       uuid: '9e5f7bc0e475c214',
//       version: '7.33.0',
//       lang: 'zh',
//       han: 's',
//       platform: 'android',
//       model: 'moto g stylus 5G - 2023',
//       loctype: '1',
//       os: '34',
//       appid: 'NxUUhRSQH3qPJmY2Vn%2FedRz4vrc%3D',
//       sid: 'session.v2.test.67dab5124e246ae193fe87bd',
//       admin_sid: 'session.v2.test.62ff0a0c47f4aa4e3315382b',
//     },
//     响应耗时: '360.00ms',
//     基础URL: 'http://www.litatom.com/api/sns/v1/lit/user/phone_login',
//     接口名称: '手机登录获取session',
//     断言失败数: '0',
//     断言通过数: '0',
//     请求ID: 'request-26bf709a-0960-4aa5-9765-5f36bf518a75',
//     请求URL:
//       'http://www.litatom.com/api/sns/v1/lit/user/phone_login?loc=CN&uuid=9e5f7bc0e475c214&version=7.33.0&lang=zh&han=s&platform=android&model=moto%20g%20stylus%205G%20-%202023&loctype=1&os=34&appid=NxUUhRSQH3qPJmY2Vn%2FedRz4vrc%3D&sid=session.v2.test.67dab5124e246ae193fe87bd&version=6.70.1&admin_sid=session.v2.test.62ff0a0c47f4aa4e3315382b',
//     请求方法: 'POST',
//     返回数据大小: '4.81KB',
//   },
//   {
//     HTTP状态码: '404',
//     URL参数: {
//       admin_sid: 'session.v2.test.62ff0a0c47f4aa4e3315382b',
//       appid: 'NxUUhRSQH3qPJmY2Vn/edRz4vrc=',
//       han: 's',
//       lang: 'zh',
//       loc: 'CN',
//       loctype: '1',
//       model: 'moto g stylus 5G - 2023',
//       os: '34',
//       platform: 'android',
//       sid: 'session.v2.1443646181416452482',
//       uuid: '9e5f7bc0e475c214',
//       version: ['7.33.0', '6.70.1'],
//     },
//     响应耗时: '136.00ms',
//     基础URL: 'http://www.litatom.com/api/sns/v1/lit/fed/create',
//     接口名称: '发布Feed内容',
//     断言失败数: '0',
//     断言通过数: '0',
//     请求ID: 'request-ce0c6fad-aeb8-4765-86b4-2d47a6c15075',
//     请求URL:
//       'http://www.litatom.com/api/sns/v1/lit/fed/create?sid=session.v2.1443646181416452482&loc=CN&uuid=9e5f7bc0e475c214&version=7.33.0&lang=zh&han=s&platform=android&model=moto%20g%20stylus%205G%20-%202023&loctype=1&os=34&appid=NxUUhRSQH3qPJmY2Vn%2FedRz4vrc%3D&version=6.70.1&admin_sid=session.v2.test.62ff0a0c47f4aa4e3315382b',
//     请求方法: 'POST',
//     返回数据大小: '0B',
//   },
//   {
//     HTTP状态码: '404',
//     URL参数: {
//       loc: 'CN',
//       uuid: '9e5f7bc0e475c214',
//       version: '7.33.0',
//       lang: 'zh',
//       han: 's',
//       platform: 'android',
//       model: 'moto g stylus 5G - 2023',
//       loctype: '1',
//       os: '34',
//       appid: 'NxUUhRSQH3qPJmY2Vn%2FedRz4vrc%3D',
//       sid: 'session.v2.1443646181416452482',
//       admin_sid: 'session.v2.test.62ff0a0c47f4aa4e3315382b',
//     },
//     响应耗时: '119.00ms',
//     基础URL: 'http://www.litatom.com/api/sns/v1/lit/feed/react/',
//     接口名称: 'Feed点赞',
//     断言失败数: '0',
//     断言通过数: '0',
//     请求ID: 'request-be6b8e1f-182a-4d1f-b5be-7be311fe6b6c',
//     请求URL:
//       'http://www.litatom.com/api/sns/v1/lit/feed/react/?sid=session.v2.1443646181416452482&loc=CN&uuid=9e5f7bc0e475c214&version=7.33.0&lang=zh&han=s&platform=android&model=moto%20g%20stylus%205G%20-%202023&loctype=1&os=34&appid=NxUUhRSQH3qPJmY2Vn%2FedRz4vrc%3D&sid=session.v2.test.67dab5124e246ae193fe87bd&version=6.70.1&admin_sid=session.v2.test.62ff0a0c47f4aa4e3315382b',
//     请求方法: 'POST',
//     返回数据大小: '0B',
//   },
//   {
//     HTTP状态码: '404',
//     URL参数: {
//       loc: 'CN',
//       uuid: '9e5f7bc0e475c214',
//       version: '7.33.0',
//       lang: 'zh',
//       han: 's',
//       platform: 'android',
//       model: 'moto g stylus 5G - 2023',
//       loctype: '1',
//       os: '34',
//       appid: 'NxUUhRSQH3qPJmY2Vn%2FedRz4vrc%3D',
//       sid: 'session.v2.1443646181416452482',
//       admin_sid: 'session.v2.test.62ff0a0c47f4aa4e3315382b',
//     },
//     响应耗时: '108.00ms',
//     基础URL: 'http://www.litatom.com/api/sns/v1/lit/feed/react/',
//     接口名称: 'Feed点赞',
//     断言失败数: '1',
//     断言详情内容:
//       "AssertionError: expected undefined to be one of [ '0', '-15' ]\\n                       at Object.eval sandbox-script.js:1:17)",
//     断言详情名称: '$.result In List',
//     断言详情结果: '失败',
//     断言通过数: '0',
//     请求ID: 'request-4cc99816-14e5-4112-ab6d-1d42e0349e0a',
//     请求URL:
//       'http://www.litatom.com/api/sns/v1/lit/feed/react/?sid=session.v2.1443646181416452482&loc=CN&uuid=9e5f7bc0e475c214&version=7.33.0&lang=zh&han=s&platform=android&model=moto%20g%20stylus%205G%20-%202023&loctype=1&os=34&appid=NxUUhRSQH3qPJmY2Vn%2FedRz4vrc%3D&sid=session.v2.test.67dab5124e246ae193fe87bd&version=6.70.1&admin_sid=session.v2.test.62ff0a0c47f4aa4e3315382b',
//     请求方法: 'POST',
//     返回数据大小: '0B',
//   },
// ]
const route = useRoute()

// 计算属性
const failedCount = computed(() => {
  console.log(data.value)
  return data.value.filter(
    (item) => item.断言失败数 !== '0' || item.HTTP状态码 !== '200',
  ).length
})

const successRate = computed(() => {
  if (data.value.length === 0) return 100
  return Math.round((1 - failedCount.value / data.value.length) * 100)
})

// 方法定义
const hasAssertionDetail = (row: ApiTestData): boolean => {
  // return !!(row.断言详情内容 || row.断言详情名称 || row.断言详情结果)
  return row.HTTP状态码 != '200' || row.断言失败数 != '0'
}
const hasAsserDetail = (row: ApiTestData): boolean => {
  // return !!(row.断言详情内容 || row.断言详情名称 || row.断言详情结果)
  return row.断言失败数 != '0'
}
const getRowClassName = ({ row }: { row: ApiTestData }) => {
  return hasAssertionDetail(row) ? 'highlight-row' : ''
}

const getMethodType = (method: string) => {
  const types: { [key: string]: string } = {
    GET: 'primary',
    POST: 'success',
    PUT: 'warning',
    DELETE: 'danger',
    PATCH: 'info',
  }
  return types[method] || 'info'
}

const getStatusType = (status: string) => {
  const statusCode = parseInt(status)
  if (statusCode >= 200 && statusCode < 300) return 'success'
  if (statusCode >= 400 && statusCode < 500) return 'warning'
  if (statusCode >= 500) return 'danger'
  return 'info'
}

const formatUrl = (url: string) => {
  if (url.length > 50) {
    return url.substring(0, 50) + '...'
  }
  return url
}

const handleRowClick = (row: ApiTestData) => {
  console.log('接口详情:', row)
}

const showDetail = (row: ApiTestData) => {
  currentRow.value = row
  detailVisible.value = true
}

const loadData = async () => {
  if (!route.query.id) {
    ElMessage.error('你还没选择报告')
    return
  }
  try {
    let result = await reqGetOneApiReportInfo(route.query.id)
    if (result.code == 200) {
      // console.log(result.data)
      // console.log(JSON.parse(result.data.URL).接口测试详情)
      data.value = JSON.parse(result.data.URL).接口测试详情
      // ElMessage.success(result.msg)
    } else {
      ElMessage.error(result.msg)
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败，请重试')
  }
}

// 生命周期
onMounted(() => {
  // 组件挂载时自动加载数据
  loadData()
})
</script>
  
  <style scoped>
.api-test-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

/* 高亮行样式 */
:deep(.highlight-row) {
  background-color: #fff2f0 !important;
}

:deep(.highlight-row:hover > td) {
  background-color: #ffeae6 !important;
}

/* 高亮文本 */
.highlight-text {
  color: #ff4d4f;
  font-weight: 600;
}

.error-count {
  color: #ff4d4f;
  font-weight: bold;
  font-size: 14px;
}

/* 高亮标签 */
.highlight-tag {
  border: 2px solid #ff4d4f;
  font-weight: 600;
}

.detail-content {
  max-height: 60vh;
  overflow-y: auto;
}

.assertion-content,
.url-params {
  background: #f5f5f5;
  padding: 12px;
  border-radius: 4px;
  white-space: pre-wrap;
  word-break: break-all;
  font-family: 'Monaco', 'Consolas', monospace;
  font-size: 12px;
  line-height: 1.4;
  margin: 0;
}

.assertion-detail {
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .api-test-container {
    padding: 10px;
  }

  .card-header {
    flex-direction: column;
    align-items: flex-start;
  }
}
</style>